package com.xy.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.xy.constant.Constant;
import com.xy.entity.Company;
import com.xy.service.CompanyService;
import com.xy.util.DateStringUtil;
import com.xy.util.PropertiesUtil;
import com.xy.util.StringUtil;

@Controller
@Scope
public class CompanyController {
	private static Logger log = Logger.getLogger(CompanyController.class);
	@Autowired
	private CompanyService companyService;

	/**
	 * 添加企业信息
	 * 
	 * @param company
	 * @param result
	 * @param modelMap
	 * @param imgFile
	 * @return
	 */
	@RequestMapping(value = "addCompany", method = RequestMethod.POST)
	public String addCompany(@Validated Company company, BindingResult result, ModelMap modelMap, @RequestParam("imagefile") CommonsMultipartFile imgFile) {
		company.setCreateTime(new Date());
		company.setCreateID(1);
		Map<String, String> errorMap = new HashMap<String, String>();
		if (result.hasErrors()) {
			List<FieldError> fieldErrorList = result.getFieldErrors();
			for (FieldError fieldError : fieldErrorList) {
				String fieldName = fieldError.getField();// 属性名
				String errorMessage = fieldError.getDefaultMessage();// 错误信息
				log.info("fieldName:" + fieldName + ", errorMessage:" + errorMessage);
				errorMap.put(fieldName, errorMessage);
			}
		}
		// 图片上传处理
		String imgRealName = imgFile.getOriginalFilename();// 原始文件名
		// 新文件名
		String newFileName = DateStringUtil.getDateToString();

		String houZhui = imgRealName.substring(imgRealName.lastIndexOf("."));// 获取文件名后缀
		// 上传路径+公司文件夹+重命名
		String path = PropertiesUtil.getValue(Constant.UPLOAD_PATH) + PropertiesUtil.getValue(Constant.COMPANY_UPLOAD_PATH) + newFileName + houZhui;
		try {
			imgFile.transferTo(new File(path));// 文件上传
			company.setImgRealName(imgRealName);
			company.setImgURL(PropertiesUtil.getValue(Constant.COMPANY_UPLOAD_PATH) + newFileName + houZhui);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// ---------------文件处理结束
		modelMap.addAttribute("errorMap", errorMap);

		boolean flag = companyService.addCompany(company);
		System.out.println("~~~~~添加结果：" + flag);
		return "selectCompanyList.action";
	}

	/**
	 * 删除企业信息
	 * 
	 * @param company
	 * @return
	 */
	@RequestMapping(value = "deleCompany", method = RequestMethod.GET)
	public String deleCompany(Company company) {
		boolean flag = companyService.deleCompany(company);
		return "selectCompanyList.action";
	}

	/**
	 * 获取公司ID，查询出公司信息，然后跳转到修改页面
	 * 
	 * @param company
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "updateCompany", method = RequestMethod.GET)
	public String updateCompany(Company company, Model model) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("companyID", company.getCompanyID());
		List<Company> companyList = companyService.selectCompanyList(map);
		company = companyList.get(0);
		model.addAttribute("company", company);
		return "pages/backend/companyModify.jsp";
	}

	/**
	 * 修改公司信息的请求
	 * 
	 * @param company
	 * @param result
	 * @param modelMap
	 * @param imgFile
	 * @return
	 */
	@RequestMapping(value = "updateCompanyAction", method = RequestMethod.POST)
	public String updateCompanyAction(Company company, BindingResult result, ModelMap modelMap, @RequestParam("imagefile") CommonsMultipartFile imgFile) {
		company.setCreateID(0);
		company.setCreateTime(new Date());
		Map<String, String> errorMap = new HashMap<String, String>();
		if (result.hasErrors()) {
			List<FieldError> fieldErrorList = result.getFieldErrors();
			for (FieldError fieldError : fieldErrorList) {
				String fieldName = fieldError.getField();// 属性名
				String errorMessage = fieldError.getDefaultMessage();// 错误信息
				log.info("fieldName:" + fieldName + ", errorMessage:" + errorMessage);
				errorMap.put(fieldName, errorMessage);
			}
		}
		// 图片上传处理
		String imgRealName = imgFile.getOriginalFilename();// 原始文件名
		// 如果文件名不为空，则操作上传文件
		if (!StringUtil.isEmpty(imgRealName)) {
			// 新文件名
			String newFileName = DateStringUtil.getDateToString();

			String houZhui = imgRealName.substring(imgRealName.lastIndexOf("."));// 获取文件名后缀
			// 上传路径+公司文件夹+重命名
			String path = PropertiesUtil.getValue(Constant.UPLOAD_PATH) + PropertiesUtil.getValue(Constant.COMPANY_UPLOAD_PATH) + newFileName + houZhui;
			try {
				imgFile.transferTo(new File(path));// 文件上传
				company.setImgRealName(imgRealName);
				company.setImgURL(PropertiesUtil.getValue(Constant.COMPANY_UPLOAD_PATH) + newFileName + houZhui);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		// ---------------文件处理结束
		modelMap.addAttribute("errorMap", errorMap);
		// 修改成功以后跳转到查询所有公司信息页面
		log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~company: " + company);

		if (companyService.updateCompanyByID(company)) {
			return "selectCompanyList.action";
		}
		modelMap.addAttribute("company", company);
		return "pages/backend/companyModify.jsp";
	}

	/**
	 * 查询所有企业信息
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "selectCompanyList", method = { RequestMethod.GET, RequestMethod.POST })
	public String selectCompanyList(Model model, HttpSession session) {
		List<Company> companyList = companyService.selectCompanyList(null);
		model.addAttribute("companyList", companyList);
		return "pages/backend/companyManage.jsp";
	}

	/**
	 * 察看企业详情
	 * 
	 * @param company
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "selectCompanyDetail", method = RequestMethod.GET)
	public String selectCompanyDetail(Company company, Model model) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("companyID", company.getCompanyID());
		List<Company> companyList = companyService.selectCompanyList(map);
		Company companyDetail = companyList.get(0);
		model.addAttribute("company", companyDetail);
		return "pages/backend/companyDetail.jsp";
	}

	/**
	 * 检验企业名称是否存在
	 * 
	 * @param companyName
	 * @return
	 */
	@RequestMapping(value = "ajaxCheckCompanyNameSame", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	String ajaxCheckCompanyNameSame(int companyID, String companyName) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("companyName", companyName);
		List<Company> companyList = companyService.selectCompanyList(map);
		if (companyList.size() > 0 && companyList.get(0).getCompanyID() != companyID) {
			// 存在则表示该名称已经存在
			return "error";
		}
		return "success";
	}

}
